# 食物管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import FoodCategories, Foods

# 食物管理
def index(request, pIndex=1):
    """食物列表页"""
    # 关键：预加载category关联，确保能获取到category_name
    flist = Foods.objects.select_related('category').all()  # 优化关联查询
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            flist = flist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        flist = flist.filter(
            Q(food_name__contains=kw) | 
            Q(description__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 类别筛选（使用category_id匹配）
    cid = request.GET.get('category', '')
    if cid:
        flist = flist.filter(category_id=cid)  # 用category_id筛选
        mywhere.append(f'category={cid}')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(flist, 5)  # 每页5条
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 获取所有类别（用于筛选框）
    categories = FoodCategories.objects.all()
    # 调试：打印类别数量和内容（在控制台查看是否有数据）
    print(f"类别数量：{categories.count()}")
    for cat in categories[:5]:  # 打印前5个类别
        print(f"类别ID：{cat.category_id}，名称：{cat.category_name}")
    
    context = {
        "foodlist": list2,
        'categories': categories,  # 传递类别数据到模板
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_cid': cid  # 用于保持筛选状态
    }
    return render(request, "myadmin/foods/index.html", context)

def add(request):
    """加载食物添加表单"""
    categories = FoodCategories.objects.all()
    context = {'categories': categories}
    return render(request, "myadmin/foods/add.html", context)

def insert(request):
    """执行食物添加"""
    try:
        ob = Foods()
        ob.food_name = request.POST.get('food_name')
        ob.category_id = request.POST.get('category_id')
        ob.calories_per_100g = request.POST.get('calories_per_100g')
        ob.protein_per_100g = request.POST.get('protein_per_100g')
        ob.fat_per_100g = request.POST.get('fat_per_100g')
        ob.carbs_per_100g = request.POST.get('carbs_per_100g')
        ob.fiber_per_100g = request.POST.get('fiber_per_100g', 0)
        ob.sugar_per_100g = request.POST.get('sugar_per_100g', 0)
        ob.sodium_per_100g = request.POST.get('sodium_per_100g', 0)
        ob.is_vegetarian = request.POST.get('is_vegetarian', False)
        ob.is_vegan = request.POST.get('is_vegan', False)
        ob.is_gluten_free = request.POST.get('is_gluten_free', False)
        ob.description = request.POST.get('description')
        ob.image_url = request.POST.get('image_url')
        ob.save()
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context)

def edit(request, fid=0):
    """加载食物编辑表单"""
    try:
        ob = Foods.objects.get(food_id=fid)
        categories = FoodCategories.objects.all()
        context = {'food': ob, 'categories': categories}
        return render(request, "myadmin/foods/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的信息！"}
    return render(request, "myadmin/info.html", context)

def update(request, fid):
    """执行食物编辑（修复版）"""
    try:
        # 1. 获取食物对象
        ob = Foods.objects.get(food_id=fid)
        
        # 2. 验证必填字段
        required_fields = {
            'food_name': '食物名称',
            'category_id': '所属类别',
            'calories_per_100g': '热量'
        }
        for field, label in required_fields.items():
            if not request.POST.get(field):
                raise ValueError(f'{label}为必填项！')
        
        # 3. 处理数值字段（转换为正确类型）
        numeric_fields = {
            'calories_per_100g': float,
            'protein_per_100g': float,
            'fat_per_100g': float,
            'carbs_per_100g': float,
            'fiber_per_100g': float,
            'sugar_per_100g': float,
            'sodium_per_100g': float
        }
        for field, converter in numeric_fields.items():
            value = request.POST.get(field, 0)
            try:
                # 转换为对应类型（如字符串转float/int）
                setattr(ob, field, converter(value) if value else 0)
            except ValueError:
                raise ValueError(f'{field}格式错误，需输入数字！')
        
        # 4. 处理字符串字段
        ob.food_name = request.POST.get('food_name').strip()
        ob.description = request.POST.get('description', '').strip()
        ob.image_url = request.POST.get('image_url', '').strip()
        
        # 5. 处理外键（验证类别ID是否存在）
        category_id = request.POST.get('category_id')
        if not FoodCategories.objects.filter(category_id=category_id).exists():
            raise ValueError(f'所属类别不存在！')
        ob.category_id = category_id
        
        # 6. 处理复选框（转换为布尔值：勾选时表单提交'on'，否则为False）
        ob.is_vegetarian = request.POST.get('is_vegetarian') == 'on'
        ob.is_vegan = request.POST.get('is_vegan') == 'on'
        ob.is_gluten_free = request.POST.get('is_gluten_free') == 'on'
        
        # 7. 保存数据
        ob.save()
        context = {'info': "修改成功！"}
    
    except Foods.DoesNotExist:
        context = {'info': "修改失败：食物不存在！"}
    except ValueError as e:
        # 捕获数据验证错误（如必填项缺失、格式错误）
        context = {'info': f"修改失败：{str(e)}"}
    except Exception as e:
        # 捕获其他未知错误（如数据库约束错误）
        print(f"修改错误详情：{str(e)}")  # 控制台输出详细错误
        context = {'info': f"修改失败：{str(e)}"}  # 显示具体错误原因
    
    return render(request, "myadmin/info.html", context)

def delete(request, fid=0):
    """执行食物删除"""
    try:
        ob = Foods.objects.get(food_id=fid)
        ob.delete()
        context = {'info': "删除成功！"}
    except Foods.DoesNotExist:
        context = {'info': "删除失败：食物不存在！"}
    except Exception as err:
        print(f"删除食物时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)